package api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import appmodel.AppUserLabel;
import appmodel.JsonArrayResult;
import appmodel.JsonModel;
import appmodel.OrderListParams;
import appmodel.OrderNumber;
import appmodel.UserOrderDetail;
import common.StringUtil;
import model.Comment;
import model.Order;
import model.User;
import net.sf.json.JSONObject;
import service.CommentService;
import service.OrderService;
import service.UserService;

@Controller
@RequestMapping({ "/order" })
public class OrderController {

	@Autowired
	private OrderService orderService;

	@Autowired
	private CommentService commentService;

	@Autowired
	private UserService userService;

	@RequestMapping(value = { "/list" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JSONObject getOrderList(HttpServletRequest request, JsonModel jsonModel, HttpServletResponse response,
			@RequestParam(value = "userId", required = false) long userId,
			@RequestParam(value = "orderType", required = false) int orderType,
			@RequestParam(value = "pageNo", required = false) int pageNo,
			@RequestParam(value = "pageSize", required = false) int pageSize) {

		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
		response.addHeader("Access-Control-Max-Age", "7200");// 120 min

		OrderListParams orderListParams = new OrderListParams();
		orderListParams.setUserId(userId);
		int offset = (pageNo - 1) * pageSize;
		orderListParams.setPageNo(offset);
		orderListParams.setPageSize(pageSize);
		List<Order> listOrder;
		if (orderType == 1 || orderType == 2) {// 如果是1或者2的话，是抢左右的订单
			orderListParams.setOrderType(1);
			if(orderType == 1) {
				orderListParams.setType("0");
			}else if(orderType == 2) {
				orderListParams.setType("1");
			}
			listOrder = this.orderService.getOrderList(orderListParams);
		} else {
			orderListParams.setOrderType(orderType);
			listOrder = this.orderService.getMyOrderList(orderListParams);
		}

		JsonArrayResult jsonArrayResult = new JsonArrayResult();
		jsonArrayResult.setJsonArrayResult(listOrder);

		if (null != listOrder) {
			jsonModel.setSuccess(true);
			jsonModel.setMsg("查询成功");
			jsonModel.setjData(jsonArrayResult);
			jsonModel.setToken("");
		} else {
			jsonModel.setSuccess(false);
			jsonModel.setMsg("查询失败");
			jsonModel.setjData(jsonArrayResult);
			jsonModel.setToken("");
		}

		return JSONObject.fromObject(jsonModel);
	}

	// H5查询订单列表的接口
	@RequestMapping(value = { "/list/user" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JSONObject getUserOrderList(HttpServletRequest request, JsonModel jsonModel, HttpServletResponse response,
			@RequestParam(value = "userId", required = false) long userId,
			@RequestParam(value = "orderType", required = false) int orderType,
			@RequestParam(value = "pageNo", required = false) int pageNo,
			@RequestParam(value = "pageSize", required = false) int pageSize) {

		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
		response.addHeader("Access-Control-Max-Age", "7200");// 120 min

		OrderListParams orderListParams = new OrderListParams();
		orderListParams.setUserId(userId);
		orderListParams.setOrderType(orderType);
		int offset = (pageNo - 1) * pageSize;
		orderListParams.setPageNo(offset);
		orderListParams.setPageSize(pageSize);
		List<Order> listOrder;
		listOrder = this.orderService.getUserOrderList(orderListParams);

		JsonArrayResult jsonArrayResult = new JsonArrayResult();
		jsonArrayResult.setJsonArrayResult(listOrder);

		// List<Order> map = this.orderService.getOrderList(orderListParams);

		if (null != listOrder) {
			jsonModel.setSuccess(true);
			jsonModel.setMsg("查询成功");
			jsonModel.setjData(jsonArrayResult);
			jsonModel.setToken("");
		} else {
			jsonModel.setSuccess(false);
			jsonModel.setMsg("查询失败");
			jsonModel.setjData(jsonArrayResult);
			jsonModel.setToken("");
		}

		return JSONObject.fromObject(jsonModel);
	}

	@RequestMapping(value = { "/detail" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JSONObject getOrderDetail(HttpServletRequest request, JsonModel jsonModel, HttpServletResponse response,
			@RequestParam(value = "orderId", required = false) String orderId) {
		Order orderDetail = this.orderService.getOrderDetail(orderId);

		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
		response.addHeader("Access-Control-Max-Age", "7200");// 120 min

		if (null != orderDetail) {
			jsonModel.setSuccess(true);
			jsonModel.setMsg("查询成功");
			jsonModel.setjData(orderDetail);
			jsonModel.setToken("");
		} else {
			jsonModel.setSuccess(false);
			jsonModel.setMsg("查询失败");
			jsonModel.setjData(orderDetail);
			jsonModel.setToken("");
		}

		return JSONObject.fromObject(jsonModel);
	}

	@RequestMapping(value = { "/detail/user" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JSONObject getOrderDetailUser(HttpServletRequest request, JsonModel jsonModel, HttpServletResponse response,
			@RequestParam(value = "orderId", required = false) String orderId) {

		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
		response.addHeader("Access-Control-Max-Age", "7200");// 120 min

		Order orderDetail = this.orderService.getOrderDetail(orderId);
		UserOrderDetail userOrderDetail = new UserOrderDetail();
		userOrderDetail.setOrder(orderDetail);

		if (null != orderDetail) {
			long orderNumberAll = this.orderService.getOrderAllNumber(orderDetail.getOrder_get_user_id());
			long orderNumberSuccess = this.orderService.getOrderSuccessNumber(orderDetail.getOrder_get_user_id());

			Integer averageScore = commentService.getCommentAverageScoreByUser(orderDetail.getOrder_get_user_id());
			if (null == averageScore) {
				averageScore = 0;
			}

			userOrderDetail.setAverageScore(averageScore);
			userOrderDetail.setOrderNumberAll(orderNumberAll);
			userOrderDetail.setOrderNumberSuccess(orderNumberSuccess);
			List<AppUserLabel> list = this.userService.getMyLabels(orderDetail.getOrder_get_user_id());
			userOrderDetail.setLables(list);
		}

		if (null != orderDetail) {
			jsonModel.setSuccess(true);
			jsonModel.setMsg("查询成功");
			jsonModel.setjData(userOrderDetail);
			jsonModel.setToken("");
		} else {
			jsonModel.setSuccess(false);
			jsonModel.setMsg("查询失败");
			jsonModel.setjData("");
			jsonModel.setToken("");
		}

		return JSONObject.fromObject(jsonModel);
	}

	@RequestMapping(value = { "/orderStateChange" }, method = {
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JSONObject modifyOrderState(HttpServletRequest request, JsonModel jsonModel, HttpServletResponse response,
			@RequestParam(value = "orderId", required = false) String orderId,
			@RequestParam(value = "userId", required = false) String userId,
			@RequestParam(value = "orderState", required = false) int orderState) {

		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
		response.addHeader("Access-Control-Max-Age", "7200");// 120 min

		Order order = this.orderService.getOrderDetail(orderId);
		User userNew = null;
		if (!StringUtil.isEmpty(userId)) {
			userNew = this.userService.getUserInfo(Long.parseLong(userId));
		}

		if (null == order) {// 如果订单为空的话
			jsonModel.setSuccess(false);
			jsonModel.setMsg("该订单不存在");
			jsonModel.setjData("");
			jsonModel.setToken("");

			return JSONObject.fromObject(jsonModel);
		} else {
			if (orderState == 3) {// 如果是抢单的话，如果是已经抢过而且取消的话，不能抢单
				String cancleOrderUserIds = order.getCancleOrderUserIds();
				if (!StringUtil.isEmpty(cancleOrderUserIds)) {
					String[] cancleUserIds = cancleOrderUserIds.split(",");
					for (int i = 0; i < cancleUserIds.length; i++) {
						if (userId.equals(cancleUserIds[i])) {// 如果相同的话，
							jsonModel.setSuccess(false);
							jsonModel.setMsg("您已经取消过该订单，不能再抢");
							jsonModel.setjData("");
							jsonModel.setToken("");
							return JSONObject.fromObject(jsonModel);
						}
					}
				}

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("orderId", orderId);
				map.put("state", "" + orderState);
				map.put("userName", "" + userNew.getUserName());
				map.put("userPhone", "" + userNew.getPhone());
				map.put("order_get_user_id", userId);

				this.orderService.modifyOrderState(map);

				jsonModel.setSuccess(true);
				jsonModel.setMsg("修改成功");
				jsonModel.setjData("");
				jsonModel.setToken("");

				return JSONObject.fromObject(jsonModel);
			} else if (orderState == 7) {// 如果是取消订单
				String cancleOrderUserIds = order.getCancleOrderUserIds();
				long orderGetUserId = order.getOrder_get_user_id();
				long userIdLong = Long.parseLong(userId);
				if (userIdLong == orderGetUserId) {// 如果是接单者取消订单,cancleOrderUserIds的字段添加getuserId
					if (StringUtil.isEmpty(cancleOrderUserIds)) {
						cancleOrderUserIds = "" + orderGetUserId;
					} else {
						cancleOrderUserIds = cancleOrderUserIds + "," + orderGetUserId;
					}

					Map<String, Object> map = new HashMap<String, Object>();
					map.put("orderId", orderId);
					map.put("state", "" + 7);
					map.put("userName", "");
					map.put("userPhone", "");
					map.put("cancleOrderUserIds", "" + cancleOrderUserIds);

					this.orderService.modifyOrderState(map);
					
					//添加差评（待测试）
					Comment comment = new Comment();
					comment.setCommentCreatDate(new Date());
					comment.setCommentedUserid(Long.parseLong(userId));
					comment.setScore(1);
					comment.setCommentOrderId(orderId);
					commentService.addComment(comment);
					
					jsonModel.setSuccess(true);
					jsonModel.setMsg("修改成功");
					jsonModel.setjData("");
					jsonModel.setToken("");

					return JSONObject.fromObject(jsonModel);
				} else {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("orderId", orderId);
					map.put("state", "" + 7);
					map.put("userName", "");
					map.put("userPhone", "");

					this.orderService.modifyOrderState(map);

					jsonModel.setSuccess(true);
					jsonModel.setMsg("修改成功");
					jsonModel.setjData("");
					jsonModel.setToken("");

					return JSONObject.fromObject(jsonModel);
				}
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("orderId", orderId);
				map.put("state", "" + orderState);

				this.orderService.modifyOrderState(map);

				jsonModel.setSuccess(true);
				jsonModel.setMsg("修改成功");
				jsonModel.setjData("");
				jsonModel.setToken("");

				return JSONObject.fromObject(jsonModel);
			}

		}
	}

	// 获取个人中心订单的数量
	@RequestMapping(value = { "/orderNumber" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JSONObject getOrderNumber(HttpServletRequest request, JsonModel jsonModel, HttpServletResponse response,
			@RequestParam(value = "userId", required = false) long userId) {

		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
		response.addHeader("Access-Control-Max-Age", "7200");// 120 min

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);

		long orderNumberAll = this.orderService.getOrderAllNumber(userId);
		long orderNumberSuccess = this.orderService.getOrderSuccessNumber(userId);
		long orderNumberFail = this.orderService.getOrderFailNumber(userId);
		long orderNumberIng = this.orderService.getOrderIngNumber(userId);

		OrderNumber orderNumber = new OrderNumber();
		orderNumber.setOrderAllNumber(orderNumberAll);
		orderNumber.setOrderSuccessNumber(orderNumberSuccess);
		orderNumber.setOrderFailNumber(orderNumberFail);
		orderNumber.setOrderIngNumber(orderNumberIng);

		jsonModel.setSuccess(true);
		jsonModel.setMsg("修改成功");
		jsonModel.setjData(orderNumber);
		jsonModel.setToken("");

		return JSONObject.fromObject(jsonModel);
	}

}